package com.tboss.template.common.dwr;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;

import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.directwebremoting.annotations.RemoteMethod;
import org.directwebremoting.annotations.RemoteProxy;
import org.springframework.beans.factory.annotation.Autowired;

import com.tboss.template.system.dao.CodeDao;
import com.tboss.template.system.dao.CodeTypeDao;
import com.tboss.template.system.dao.MappingGroupFunctionDao;
import com.tboss.template.system.dto.CodeDto;
import com.tboss.template.system.dto.CodeTypeDto;

@RemoteProxy(name="checkInternalCode")
public class CheckInternalCode {
	
	@Autowired CodeTypeDao codeTypeDao;
	@Autowired CodeDao codeDao;
	@Autowired MappingGroupFunctionDao mapGrpFnDao;
	
	@RemoteMethod
	public String getNotUsedCodeList(HashMap<String, String> chkFields){//String codeType
		String rtnValue = null;
		
		try {
			CodeDto dto = new CodeDto();
			dto.setCdTpId(chkFields.get("cdTpId"));
			if(chkFields.get("actionType").equals("revise")){
				dto.setCdId(chkFields.get("cdId"));
			}
			List<CodeDto> list = this.codeDao.getAvailableCodeList(dto);
			
			if(list != null && list.size() > 0){
				StringBuffer tmpValue = new StringBuffer();
				tmpValue.append(new ObjectMapper().writeValueAsString(list));
				
				rtnValue = tmpValue.toString();
			}
			
		} catch (JsonGenerationException e) { e.printStackTrace();
		} catch (JsonMappingException e) { e.printStackTrace();
		} catch (IOException e) { e.printStackTrace();
		} catch (Exception e) { e.printStackTrace();
		}
		
		return rtnValue;
	}
	
	@RemoteMethod
	public String getCdTpRegExpr(String cdTpId){
		String rtnValue = null;
		
		CodeTypeDto dto = this.codeTypeDao.getCodeTypeInfo(cdTpId);
		if(dto != null) rtnValue = dto.getCdTpRegExpr();
		
		return rtnValue;
	}
	
	@RemoteMethod
	public String getUsedLowLevelGrpFnList(HashMap<String, String> chkFields){//String codeType
		String rtnValue = null;
		
		try {
			List<HashMap<String, String>> list = this.mapGrpFnDao.getUsedLowLevelGrpFnList(chkFields.get("cdId"));
			
			if(list != null && list.size() > 0){
				StringBuffer tmpValue = new StringBuffer();
				tmpValue.append(new ObjectMapper().writeValueAsString(list));
				
				rtnValue = tmpValue.toString();
			}
			
		} catch (JsonGenerationException e) { e.printStackTrace();
		} catch (JsonMappingException e) { e.printStackTrace();
		} catch (IOException e) { e.printStackTrace();
		} catch (Exception e) { e.printStackTrace();
		}
		
		return rtnValue;
	}
	
}
